<script setup lang="ts">
import { Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'
import AppointmentSelectDialog from './AppointmentSelectDialog.vue'

interface Props {
  modelValue: boolean
  batchId: string
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 数据状态
const loading = ref(false)
const appointmentsLoading = ref(false)
const batch = ref(null)
const appointments = ref([])
const selectedAppointments = ref([])

// 对话框状态
const showSelectDialog = ref(false)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

// 加载数据
async function loadData() {
  if (!props.batchId)
    return

  await Promise.all([
    loadBatch(),
    loadAppointments(),
  ])
}

// 加载批次信息
async function loadBatch() {
  loading.value = true
  try {
    const response = await window.api.batch.get(props.batchId)
    if (response.success) {
      batch.value = response.data
    }
    else {
      ElMessage.error(response.error || '加载批次信息失败')
    }
  }
  catch (error) {
    console.error('加载批次信息失败:', error)
    ElMessage.error('加载批次信息失败')
  }
  finally {
    loading.value = false
  }
}

// 加载预约记录
async function loadAppointments() {
  if (!props.batchId)
    return

  appointmentsLoading.value = true
  try {
    const response = await window.api.batch.getAppointments(props.batchId)
    if (response.success) {
      appointments.value = response.data
    }
    else {
      ElMessage.error(response.error || '加载预约记录失败')
    }
  }
  catch (error) {
    console.error('加载预约记录失败:', error)
    ElMessage.error('加载预约记录失败')
  }
  finally {
    appointmentsLoading.value = false
  }
}

// 选择变化
function handleSelectionChange(selection) {
  selectedAppointments.value = selection
}

// 添加预约记录
function addAppointments() {
  showSelectDialog.value = true
}

// 移除单个预约记录
async function removeAppointment(appointment) {
  try {
    await ElMessageBox.confirm(
      `确定要从批次中移除预约记录 "${appointment.sequence_number}" 吗？`,
      '确认移除',
      {
        confirmButtonText: '移除',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const response = await window.api.batch.removeAppointments(props.batchId, [appointment.id])
    if (response.success) {
      ElMessage.success('移除成功')
      loadData() // 重新加载数据
    }
    else {
      ElMessage.error(response.error || '移除失败')
    }
  }
  catch (error) {
    if (error !== 'cancel') {
      console.error('移除预约记录失败:', error)
      ElMessage.error('移除失败')
    }
  }
}

// 批量移除预约记录
async function removeSelectedAppointments() {
  try {
    await ElMessageBox.confirm(
      `确定要从批次中移除选中的 ${selectedAppointments.value.length} 个预约记录吗？`,
      '确认批量移除',
      {
        confirmButtonText: '移除',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const appointmentIds = selectedAppointments.value.map(item => item.id)
    const response = await window.api.batch.removeAppointments(props.batchId, appointmentIds)

    if (response.success) {
      ElMessage.success('批量移除成功')
      selectedAppointments.value = []
      loadData() // 重新加载数据
    }
    else {
      ElMessage.error(response.error || '批量移除失败')
    }
  }
  catch (error) {
    if (error !== 'cancel') {
      console.error('批量移除失败:', error)
      ElMessage.error('批量移除失败')
    }
  }
}

// 工具函数
function getBatchStatusType(status) {
  const types = {
    created: 'info',
    running: 'warning',
    paused: 'warning',
    completed: 'success',
    failed: 'danger',
  }
  return types[status] || ''
}

function getBatchStatusText(status) {
  const texts = {
    created: '已创建',
    running: '运行中',
    paused: '已暂停',
    completed: '已完成',
    failed: '失败',
  }
  return texts[status] || status
}

function getProgressPercentage() {
  if (!batch.value || batch.value.total_count === 0)
    return 0
  const processed = batch.value.success_count + batch.value.failed_count
  return Math.round((processed / batch.value.total_count) * 100)
}

function getProgressStatus() {
  if (!batch.value)
    return undefined
  const statusMap = {
    completed: 'success',
    failed: 'exception',
    running: undefined,
    paused: undefined,
  }
  return statusMap[batch.value.status]
}

function getPriorityType(priority) {
  const types = { 1: 'danger', 2: 'warning', 3: '', 4: 'info', 5: 'success' }
  return types[priority] || ''
}

function getStatusType(status) {
  const types = {
    pending: 'warning',
    booked: 'success',
    confirmed: 'success',
    cancelled: 'info',
    failed: 'danger',
  }
  return types[status] || ''
}

function getStatusText(status) {
  const texts = {
    pending: '待处理',
    booked: '已预约',
    confirmed: '已确认',
    cancelled: '已取消',
    failed: '失败',
  }
  return texts[status] || status
}

function formatDateTime(dateStr) {
  if (!dateStr)
    return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}
</script>

<template>
  <el-dialog
    v-model="visible"
    title="批次详情"
    width="1200px"
    @open="loadData"
  >
    <div v-loading="loading">
      <!-- 批次信息 -->
      <div v-if="batch" class="batch-info">
        <el-descriptions title="批次信息" :column="2" border>
          <el-descriptions-item label="批次名称">
            {{ batch.name }}
          </el-descriptions-item>
          <el-descriptions-item label="批次状态">
            <el-tag :type="getBatchStatusType(batch.status)">
              {{ getBatchStatusText(batch.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="批次描述">
            {{ batch.description || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="并发限制">
            {{ batch.concurrent_limit }}
          </el-descriptions-item>
          <el-descriptions-item label="失败重试">
            {{ batch.retry_failed ? '是' : '否' }}
          </el-descriptions-item>
          <el-descriptions-item label="自动释放占号">
            {{ batch.auto_release_placeholder ? '是' : '否' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(batch.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatDateTime(batch.started_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 统计信息 -->
      <div v-if="batch" class="batch-stats">
        <h3>统计信息</h3>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-number">
              {{ batch.total_count }}
            </div>
            <div class="stat-label">
              总记录数
            </div>
          </div>
          <div class="stat-card success">
            <div class="stat-number">
              {{ batch.success_count }}
            </div>
            <div class="stat-label">
              成功
            </div>
          </div>
          <div class="stat-card danger">
            <div class="stat-number">
              {{ batch.failed_count }}
            </div>
            <div class="stat-label">
              失败
            </div>
          </div>
          <div class="stat-card warning">
            <div class="stat-number">
              {{ batch.pending_count }}
            </div>
            <div class="stat-label">
              待处理
            </div>
          </div>
        </div>

        <div class="progress-section">
          <el-progress
            :percentage="getProgressPercentage()"
            :status="getProgressStatus()"
            :stroke-width="20"
            text-inside
          />
        </div>
      </div>

      <!-- 预约记录列表 -->
      <div class="appointments-section">
        <div class="section-header">
          <h3>预约记录</h3>
          <div class="section-actions">
            <el-button @click="addAppointments">
              <el-icon><Plus /></el-icon>
              添加预约
            </el-button>
            <el-button @click="loadAppointments">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>

        <el-table
          v-loading="appointmentsLoading"
          :data="appointments"
          stripe
          border
          height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column prop="sequence_number" label="序号" width="120">
            <template #default="{ row }">
              <el-tag v-if="row.is_placeholder" type="warning" size="small">
                占号
              </el-tag>
              {{ row.sequence_number }}
            </template>
          </el-table-column>

          <el-table-column prop="full_name" label="姓名" width="100" />

          <el-table-column prop="passport_number" label="护照号码" width="120" />

          <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />

          <el-table-column prop="priority" label="优先级" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="getPriorityType(row.priority)" size="small">
                {{ row.priority }}级
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="appointment_status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.appointment_status)" size="small">
                {{ getStatusText(row.appointment_status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="预约信息" width="200">
            <template #default="{ row }">
              <div v-if="row.appointment_date" class="text-sm">
                <div>{{ row.appointment_date }}</div>
                <div class="text-gray-500">
                  {{ row.appointment_time }}
                </div>
                <div v-if="row.reference_number" class="text-xs text-blue-600">
                  {{ row.reference_number }}
                </div>
              </div>
              <span v-else class="text-gray-400">未预约</span>
            </template>
          </el-table-column>

          <el-table-column label="错误信息" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.error_message" class="text-sm text-red-600">
                {{ row.error_message }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="danger"
                @click="removeAppointment(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="selectedAppointments.length > 0" class="batch-actions">
          <el-button
            type="danger"
            @click="removeSelectedAppointments"
          >
            批量移除 ({{ selectedAppointments.length }})
          </el-button>
        </div>
      </div>
    </div>

    <!-- 添加预约对话框 -->
    <AppointmentSelectDialog
      v-model="showSelectDialog"
      :batch-id="batchId"
      @success="loadAppointments"
    />
  </el-dialog>
</template>

<style scoped>
.batch-info {
  margin-bottom: 24px;
}

.batch-stats {
  margin-bottom: 24px;
}

.batch-stats h3 {
  margin-bottom: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.stat-card {
  text-align: center;
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
}

.stat-card.success {
  background: #f0f9ff;
  color: #059669;
}

.stat-card.danger {
  background: #fef2f2;
  color: #dc2626;
}

.stat-card.warning {
  background: #fffbeb;
  color: #d97706;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.progress-section {
  margin-top: 16px;
}

.appointments-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.batch-actions {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
}
</style>
